/***************************************************************************
 * File name: q2.c
 * Author:  Tomer Filiba
 *          037013075
 *          sebulba@t2
 *
 * Exercise #: 3
 * Question #: 2
 * Submission Date: 01/7/07
 **************************************************************************/

/*-------------------------------------------------------------------------
  Include files:
--------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/*=========================================================================
  Constants and definitions:
==========================================================================*/
#define GREAT_SUCCESS		(0)
#define BIG_BAGA_BOOM		(1)

/*-------------------------------------------------------------------------
  Calculates the approximation of the square root of a given number
 -------------------------------------------------------------------------*/
int main(int argc, const char ** argv) 
{
	unsigned long number;
	double root, lastroot, epsilon;
	
	/* get input from user */
	printf("Number: ");
	if (scanf("%lu", &number) != 1) {
		printf("Error! Invalid input\n");
		return BIG_BAGA_BOOM;
	}
	if (number < 1) {
		printf("The number must be >= 1\n");
		return BIG_BAGA_BOOM;
	}
	
	printf("Percision: ");
	if (scanf("%lf", &epsilon) != 1) {
		printf("Error! Invalid input\n");
		return BIG_BAGA_BOOM;
	}
	if (epsilon <= 0 || epsilon >= 1) {
		printf("The precision must be 0..1\n");
		return BIG_BAGA_BOOM;
	}
	
	/* make a wild guess and start approaching sqrt(number) */
	lastroot = 1;
	root = pow(3, log10(number));
	while (fabs(root - lastroot) > epsilon) {
		lastroot = root;
		root = (lastroot + number / lastroot) / 2.0;
	}
	
	/* print the result */
	printf("The square root of %lu is %lf\n", number, root);
	return GREAT_SUCCESS;
}

/**************************************************************************
                               End of file
***************************************************************************/